package com.scale.service.conversation.service.impl;

import com.example.conversation.entity.Conversations;
import com.scale.service.conversation.mapper.ConversationsMapper;
import com.scale.service.conversation.service.ConversationsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.UUID;

/**
 * <p>
 * 对话会话表 服务实现类
 * </p>
 *
 * @author crp
 * @since 2025-09-24
 */
@Service
public class ConversationsServiceImpl extends ServiceImpl<ConversationsMapper, Conversations> implements ConversationsService {

    @Override
    public Integer getActiveConversationCount(Long characterId) {
        QueryWrapper<Conversations> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("character_id", characterId)
                   .eq("status", 1); // 1-进行中
        return Math.toIntExact(count(queryWrapper));
    }

    @Override
    public Integer getTodayConversationCount(Long characterId) {
        QueryWrapper<Conversations> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("character_id", characterId)
                   .ge("created_at", LocalDate.now().atStartOfDay());
        return Math.toIntExact(count(queryWrapper));
    }

    @Override
    public Conversations createOrGetConversation(Long userId, Long characterId) {
        System.out.println("创建或获取对话 - userId: " + userId + ", characterId: " + characterId);
        
        // 查找是否存在进行中的对话
        QueryWrapper<Conversations> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("character_id", characterId)
                   .eq("status", 1); // 1-进行中
        
        Conversations conversation = getOne(queryWrapper);
        System.out.println("查找现有对话结果: " + (conversation != null ? "找到" : "未找到"));
        
        if (conversation == null) {
            // 创建新对话
            conversation = new Conversations();
            conversation.setUserId(userId);
            conversation.setCharacterId(characterId);
            conversation.setSessionId(UUID.randomUUID().toString());
            conversation.setTitle("新对话");
            conversation.setStartTime(LocalDateTime.now());
            conversation.setStatus(1); // 1-进行中
            conversation.setTotalMessages(0);
            conversation.setCreatedAt(LocalDateTime.now());
            conversation.setUpdatedAt(LocalDateTime.now());
            
            boolean saveResult = save(conversation);
            System.out.println("保存新对话结果: " + saveResult + ", 对话ID: " + (conversation.getId()));
            
            if (!saveResult || conversation.getId() == null) {
                System.err.println("保存对话失败！");
                return null;
            }
        }
        
        return conversation;
    }
}
